package com.mccken.demo.io.socket;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2022-04-19 10:16
 **/
public class Server {

	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = new ServerSocket(9000);
		Socket socket = serverSocket.accept();

		char[] chars = new char[1024 * 1024];
		OutputStream out = socket.getOutputStream();
		InputStreamReader in = new InputStreamReader(socket.getInputStream());

		Runnable scannerRunnable = new Runnable() {
			@Override
			public void run() {
				Scanner scanner = new Scanner(System.in);
				while (scanner.hasNext()) {
					String str = scanner.nextLine();
					try {
						out.write(str.getBytes(StandardCharsets.UTF_8));
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		};

		Runnable inRunnable = new Runnable() {
			@Override
			public void run() {
				try {
					int len = in.read(chars);
					while (len > 0) {
						String resp = new String(chars, 0, len);
						System.out.println("客户端发送给服务端: " + resp);
						len = in.read(chars);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};

		new Thread(inRunnable).start();
		new Thread(scannerRunnable).start();

	}

}
